<template>
  <el-dialog
    v-model="dialogVisible"
    title="规则详情"
    width="900px"
    :close-on-click-modal="false"
  >
    <div class="rule-detail">
      <!-- 基本信息 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
            <el-tag :type="getStatusTagType(detailData.status)">
              {{ detailData.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="规则ID">{{ detailData.ruleId }}</el-descriptions-item>
          <el-descriptions-item label="规则名称">{{ detailData.ruleName }}</el-descriptions-item>
          <el-descriptions-item label="规则类型">
            <el-tag :type="getRuleTypeTagType(detailData.ruleType)">
              {{ getRuleTypeText(detailData.ruleType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(detailData.priority)">
              {{ getPriorityText(detailData.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="触发次数">{{ detailData.triggerCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="最后触发">{{ detailData.lastTriggerTime || '未触发' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
          <el-descriptions-item label="规则描述" :span="2">
            {{ detailData.description || '暂无描述' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 规则配置 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <span class="card-title">规则配置</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="config-section">
              <h4>触发条件</h4>
              <div class="code-block">
                <pre>{{ detailData.condition || '暂无条件' }}</pre>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="config-section">
              <h4>执行动作</h4>
              <div class="code-block">
                <pre>{{ detailData.action || '暂无动作' }}</pre>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 高级配置 -->
        <div class="advanced-config" v-if="hasAdvancedConfig">
          <h4>高级配置</h4>
          <el-descriptions :column="4" size="small">
            <el-descriptions-item label="执行超时" v-if="detailData.timeout">
              {{ detailData.timeout }}秒
            </el-descriptions-item>
            <el-descriptions-item label="重试次数" v-if="detailData.retryCount">
              {{ detailData.retryCount }}次
            </el-descriptions-item>
            <el-descriptions-item label="冷却时间" v-if="detailData.cooldown">
              {{ detailData.cooldown }}秒
            </el-descriptions-item>
            <el-descriptions-item label="最大触发" v-if="detailData.maxTriggers">
              {{ detailData.maxTriggers }}次
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>

      <!-- 执行历史 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">执行历史</span>
            <el-button type="primary" size="small" icon="Refresh" @click="refreshHistory">刷新</el-button>
          </div>
        </template>
        
        <el-table :data="executionHistory" style="width: 100%" max-height="300">
          <el-table-column label="执行时间" prop="executeTime" width="160" />
          <el-table-column label="执行状态" prop="status" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getExecutionStatusType(scope.row.status)">
                {{ getExecutionStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="执行结果" prop="result" show-overflow-tooltip />
          <el-table-column label="耗时" prop="duration" width="80" align="center">
            <template #default="scope">
              {{ scope.row.duration }}ms
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button type="text" size="small" @click="viewExecutionDetail(scope.row)">详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="empty-history" v-if="!executionHistory.length">
          <el-empty description="暂无执行历史" />
        </div>
      </el-card>

      <!-- 统计图表 -->
      <el-card shadow="never" class="detail-card">
        <template #header>
          <span class="card-title">执行统计</span>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number success">{{ getSuccessCount() }}</div>
              <div class="stat-label">成功执行</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number error">{{ getFailedCount() }}</div>
              <div class="stat-label">执行失败</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number info">{{ getAverageDuration() }}ms</div>
              <div class="stat-label">平均耗时</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑规则</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// Props
interface Props {
  visible: boolean
  detailData: any
  executionHistory: any[]
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  detailData: () => ({}),
  executionHistory: () => []
})

// Emits
const emit = defineEmits(['update:visible', 'edit'])

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const hasAdvancedConfig = computed(() => {
  return props.detailData.timeout || props.detailData.retryCount || 
         props.detailData.cooldown || props.detailData.maxTriggers
})

// 方法
const getStatusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}

const getRuleTypeTagType = (type: string) => {
  const typeMap = {
    device: 'primary',
    data: 'success',
    alarm: 'danger',
    scene: 'warning'
  }
  return typeMap[type] || 'info'
}

const getRuleTypeText = (type: string) => {
  const typeMap = {
    device: '设备规则',
    data: '数据规则',
    alarm: '告警规则',
    scene: '场景规则'
  }
  return typeMap[type] || type
}

const getPriorityTagType = (priority: string) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'info'
  }
  return priorityMap[priority] || 'info'
}

const getPriorityText = (priority: string) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

const getExecutionStatusType = (status: string) => {
  const statusMap = {
    success: 'success',
    failed: 'danger',
    running: 'warning',
    timeout: 'info'
  }
  return statusMap[status] || 'info'
}

const getExecutionStatusText = (status: string) => {
  const statusMap = {
    success: '成功',
    failed: '失败',
    running: '执行中',
    timeout: '超时'
  }
  return statusMap[status] || status
}

const getSuccessCount = () => {
  return props.executionHistory.filter(item => item.status === 'success').length
}

const getFailedCount = () => {
  return props.executionHistory.filter(item => item.status === 'failed').length
}

const getAverageDuration = () => {
  if (!props.executionHistory.length) return 0
  const total = props.executionHistory.reduce((sum, item) => sum + item.duration, 0)
  return Math.round(total / props.executionHistory.length)
}

const refreshHistory = () => {
  ElMessage.success('执行历史已刷新')
  // 这里可以调用API刷新执行历史数据
}

const viewExecutionDetail = (row: any) => {
  ElMessage.info(`查看执行详情: ${row.executeTime}`)
  // 这里可以打开执行详情对话框
}

const handleEdit = () => {
  emit('edit', props.detailData)
  handleClose()
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.rule-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-card {
  margin-bottom: 20px;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.config-section {
  margin-bottom: 20px;
}

.config-section h4 {
  margin: 0 0 10px 0;
  font-size: 14px;
  color: #606266;
}

.code-block {
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
  overflow-x: auto;
}

.code-block pre {
  margin: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.advanced-config {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.advanced-config h4 {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #606266;
}

.empty-history {
  text-align: center;
  padding: 40px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.success {
  color: #67c23a;
}

.stat-number.error {
  color: #f56c6c;
}

.stat-number.info {
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>